package io.noties.markwon.plugin.graphviz.span

import android.graphics.Canvas
import android.graphics.Paint
import androidx.annotation.ColorInt
import io.noties.markwon.base.image.AsyncDrawable
import io.noties.markwon.base.image.span.AsyncDrawableSpan
import io.noties.markwon.plugin.graphviz.GraphvizAsyncDrawable
import io.noties.markwon.theme.MarkwonTheme

/**
 * @since 4.3.0
 */
open class GraphvizAsyncDrawableSpan(
    theme: MarkwonTheme,
    override val drawable: AsyncDrawable,
    @param:ColorInt private val color: Int
) : AsyncDrawableSpan(theme, drawable, ALIGN_CENTER, false) {
    private var appliedTextColor: Boolean

    init {
        // if color is not 0 -> then no need to apply text color
        appliedTextColor = color != 0
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        if (!appliedTextColor && drawable.hasResult()) {
            // it is important to check for type (in case of an error, or custom placeholder or whatever
            //  this result can be of other type)
            val drawableResult = drawable.resultDrawable
            if (drawableResult is GraphvizAsyncDrawable) {
                /*val icon = drawableResult.icon()
                icon.setForeground(Color(paint.color))
                appliedTextColor = true*/
            }
        }
        super.draw(canvas, text, start, end, x, top, y, bottom, paint)
    }

    fun drawable(): AsyncDrawable {
        return drawable
    }

    @ColorInt
    fun color(): Int {
        return color
    }
}